import React, { useRef, useState } from 'react';
import { Button, Space, message, Popconfirm, Tag, Modal } from 'antd';
import { PlusOutlined, ExportOutlined, ReloadOutlined, UserOutlined, EditOutlined, KeyOutlined, DeleteOutlined, SafetyOutlined } from '@ant-design/icons';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { history } from '@umijs/max';

import LogoutButton from '@/components/LogoutButton';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { User } from '@/services/generated';

const UserList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);

  // 删除用户
  const handleDelete = async (id: number) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.users.usersDestroy({ id: Number(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('删除失败:', error);
      message.error(error?.response?.data?.message || '删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = async (selectedRowKeys: React.Key[]) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await Promise.all(
        selectedRowKeys.map(id => apiClients.users.usersDestroy({ id: Number(id) }))
      );
      message.success(`成功删除${selectedRowKeys.length}条记录`);
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 重置密码
  const handleResetPassword = async (user: User) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      const response = await apiClients.users.usersResetPasswordCreate({
        id: user.id,
        userPasswordResetRequest: {
          auto_generate: true
        }
      });

      // 显示新密码
      const responseData = response.data as any;
      Modal.success({
        title: '密码重置成功',
        width: 500,
        content: (
          <div>
            <p>用户 <strong>{user.username}</strong> 的密码已重置</p>
            <p>新密码：<strong style={{ color: '#1890ff', fontSize: '16px' }}>{responseData?.new_password}</strong></p>
            <p style={{ color: '#ff4d4f', marginTop: '16px' }}>
              ⚠️ 请将新密码告知用户，并提醒用户及时修改密码
            </p>
          </div>
        ),
        okText: '我已记录',
      });

      message.success('密码重置成功');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('重置密码失败:', error);
      message.error(error?.response?.data?.message || '重置密码失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出用户数据
  const handleExport = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.users.usersList({
        page: 1,
        pageSize: 1000, // 导出所有数据
      });

      const users = response?.data?.items || [];
      const csvContent = [
        ['ID', '用户名', '邮箱', '真实姓名', '手机号', '状态', '管理员', '创建时间'].join(','),
        ...users.map(user => [
          user.id,
          user.username,
          user.email,
          user.real_name || '',
          user.phone || '',
          user.status,
          user.is_staff ? '是' : '否',
          user.created_at ? new Date(user.created_at).toLocaleString() : ''
        ].join(','))
      ].join('\n');

      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `用户列表_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error('导出失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<User>[] = [
    { 
      title: 'ID', 
      dataIndex: 'id', 
      width: 80, 
      sorter: true,
      hideInSearch: true,
    },
    { 
      title: '用户名', 
      dataIndex: 'username', 
      ellipsis: true, 
      copyable: true,
    },
    { 
      title: '邮箱', 
      dataIndex: 'email', 
      ellipsis: true, 
      copyable: true,
    },
    { 
      title: '真实姓名', 
      dataIndex: 'real_name',
      hideInSearch: true,
    },
    { 
      title: '手机号', 
      dataIndex: 'phone',
      hideInSearch: true,
    },
    { 
      title: '状态', 
      dataIndex: 'status', 
      valueType: 'select', 
      valueEnum: { 
        active: { text: '激活', status: 'Success' },
        inactive: { text: '未激活', status: 'Default' },
        suspended: { text: '暂停', status: 'Error' },
      },
      render: (_, record) => {
        const statusMap = {
          active: <Tag color="green">激活</Tag>,
          inactive: <Tag color="default">未激活</Tag>,
          suspended: <Tag color="red">暂停</Tag>,
        };
        return statusMap[record.status as keyof typeof statusMap] || <Tag>{record.status}</Tag>;
      }
    },
    { 
      title: '管理员', 
      dataIndex: 'is_staff',
      valueType: 'select',
      valueEnum: {
        true: { text: '是', status: 'Success' },
        false: { text: '否', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={record.is_staff ? 'blue' : 'default'}>
          {record.is_staff ? '是' : '否'}
        </Tag>
      ),
      hideInSearch: true,
    },
    { 
      title: '创建时间', 
      dataIndex: 'created_at', 
      valueType: 'dateTime', 
      sorter: true,
      hideInSearch: true,
    },
    { 
      title: '最后登录', 
      dataIndex: 'last_login_at', 
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      width: 320,
      fixed: 'right',
      hideInSearch: true,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            size="small"
            icon={<UserOutlined />}
            onClick={() => history.push(`/user/detail/${record.id}`)}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => history.push(`/user/edit/${record.id}`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<SafetyOutlined />}
            onClick={() => history.push(`/user/permissions/${record.id}`)}
          >
            权限
          </Button>
          <Popconfirm
            title="确定重置该用户的密码？"
            description="重置后将生成新的随机密码，请及时告知用户"
            onConfirm={() => handleResetPassword(record)}
            okText="确定重置"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              icon={<KeyOutlined />}
              loading={loading}
            >
              重置密码
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确定删除该用户？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              loading={loading}
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer title="用户管理">
      <ProTable<User>
           scroll={{x: 'max-content'}}
        actionRef={actionRef}
        columns={columns}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        pagination={{ 
          pageSize: 20, 
          showSizeChanger: true, 
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`
        }}
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys) => {
            console.log('选中的行:', selectedRowKeys);
          },
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>已选择 {selectedRowKeys.length} 项</span>
            <Button type="link" size="small" onClick={onCleanSelected}>
              取消选择
            </Button>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => (
          <Space size={16}>
            <Popconfirm 
              title={`确定删除选中的${selectedRowKeys.length}条记录？`} 
              onConfirm={() => handleBatchDelete(selectedRowKeys)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" size="small" danger>
                批量删除
              </Button>
            </Popconfirm>
          </Space>
        )}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => history.push('/user/create')}
          >
            新增用户
          </Button>,
          <Button
            key="export"
            icon={<ExportOutlined />}
            onClick={handleExport}
            loading={loading}
          >
            导出
          </Button>,
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
          <LogoutButton key="logout" type="link" text="登出" />,
        ]}
        request={async (params, sort, filter) => {
          try {
            await autoLoginInDev();
            const response = await apiClients.users.usersList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.username || params.email, // 搜索参数
              status: params.status, // 过滤参数
              ordering: sort && Object.keys(sort).length > 0 ?
                Object.entries(sort).map(([key, value]) => value === 'ascend' ? key : `-${key}`).join(',') :
                undefined, // 排序参数
            });
            
            return {
              data: response?.data?.items || [],
              success: true,
              total: response?.data?.total || 0
            };
          } catch (error: any) {
            console.error('获取用户列表失败:', error);
            message.error('获取数据失败');
            return { data: [], success: false, total: 0 };
          }
        }}
      />
    </PageContainer>
  );
};

export default UserList;
